package com.baobaotao.dao;

import com.baobaotao.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by hduprince on 15/8/29.
 */

@Repository
public class UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public int getMatchCount(String username, String password){
        String queryForInt = "SELECT COUNT(*) FROM t_user WHERE user_name = ? AND password = ?";
        return jdbcTemplate.queryForInt(queryForInt, new Object[]{username, password});
    }

    public User findUserByUserName(final String username){
        String sql = "SELECT user_id, user_name, credits FROM t_user WHERE user_name = ?";

        final User user = new User();

        jdbcTemplate.query(sql, new Object[]{username}, new RowCallbackHandler() {
            @Override
            public void processRow(ResultSet resultSet) throws SQLException {
                user.setUserName(username);
                user.setUserId(resultSet.getInt("user_id"));
                user.setCredits(resultSet.getInt("credits"));
            }
        });
        return user;
    }

    public void updateLoginInfo(User user){
        String sql = "UPDATE t_user SET last_visit = ?, last_ip = ?, credits = ? WHERE user_id = ?";

        jdbcTemplate.update(sql, new Object[]{user.getLastVisit(), user.getLastIp(), user.getUserId()});
    }


}
